const app = getApp()
import { getShopMaterialList } from '../../../api/index'

Page({
  data: {
    safeBottom: 0,
    supplierId: '',
    isEmpty: false,
    list: [],
    currentPage: 1,
    pageSize: 15
  },
  search ({ detail }) {
    this.setData({ keyword: detail })
    this.getList()
  },
  async loadMore () {
    try {
      if (this.loading || this.alloaded) return
      this.loading = true
      let query = {
        id: this.data.supplierId,
        currentPage: this.data.currentPage,
        pageLines: this.data.pageSize,
      }
      if (this.data.keyword) query.data = this.data.keyword
      const { ResultSet } = await getShopMaterialList({ ...query })
      this.alloaded = !ResultSet.userData.data.length
      this.data.isEmpty = !ResultSet.userData.data.length
      this.setData({ isEmpty: this.data.isEmpty })
      if (ResultSet.userData.data.length) {
        this.data.currentPage = this.data.currentPage + 1
        this.data.list.push(...ResultSet.userData.data)
        this.setData({
          list: this.data.list,
          currentPage: this.data.currentPage
        })
      }
      this.loading = false
    } catch (err) {
      this.loading = false
      wx.showToast({ title: err.message || err.ResultSet.errors })
    }
  },
  async getList () {
    try {
      let query = {
        supplierId: this.data.supplierId,
        currentPage: 1,
        pageLines: this.data.pageSize
      }
      if (this.data.keyword) query.data = this.data.keyword
      const { ResultSet } = await getShopMaterialList({ ...query })
      this.data.isEmpty = ResultSet.userData.data.length && ResultSet.userData.data.length < this.data.pageSize
        if (ResultSet.userData.data.length) this.data.currentPage = 2
        this.setData({
          list: ResultSet.userData.data,
          currentPage: this.data.currentPage,
          isEmpty: this.data.isEmpty
        })
    } catch (err) {
      console.log(err)
      wx.showToast({ title: err.message || err.ResultSet.errors })
    }
  },
  onLoad ({ id }) {
    const { screenHeight, safeArea: { bottom } } = wx.$pro.getSystemInfoSync()
    this.setData({ supplierId: id, safeBottom: screenHeight - bottom })
    this.getList()
  }
})